package com.yuexun.dhdoctor.module.commun.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.baselistener.OnDataBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.config.DbConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.ChildDepartmentsBean;
import com.yuexun.dhdoctor.module.Contract.bean.GroupDataBean;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.bean.UsersBean;
import com.yuexun.dhdoctor.module.Contract.model.impl.DepartmentModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.DepartmentPresenter;
import com.yuexun.dhdoctor.module.Contract.ui.view.IDepartmentView;
import com.yuexun.dhdoctor.module.commun.adapter.DepartAndGroup_Depart_Adapter;
import com.yuexun.dhdoctor.module.commun.ui.Act_DepartAndGroup;
import com.yuexun.dhdoctor.module.commun.ui.Act_DepartAndGroup_Depart;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;


import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/3/27 0027.
 */

public class Frag_DepartAndGroup_Depart extends KJFragment implements IDepartmentView {

    @Bind(R.id.etSearch2)
    EditText etSearch2;
    @Bind(R.id.btnSearchClear)
    ImageButton btnSearchClear;
    @Bind(R.id.searchLayout)
    LinearLayout searchLayout;

    @Bind(R.id.dept_list)
    FixedSwipeListView deptList;
    @Bind(R.id.people_list)
    FixedSwipeListView peopleList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private Handler handler;

    private DepartmentPresenter presenter;
    private DepartAndGroup_Depart_Adapter adapter_dept;
    private AddMemberAdapter addMemberAdapter;

    ArrayList<People> usersBeans_origin = new ArrayList<>();
    ArrayList<People> peoples = new ArrayList<>();

    private KJDB kjdb;
    private List<GroupDataBean> datas;
    private ArrayList departmentBeans;

    private OnDataBackListener listener;
    //0：不能选择自己  1：能选择
    private int isSelectMe;

    public void setDepartment(ArrayList departmentBeans, OnDataBackListener listener, int isSelectMe) {
        this.departmentBeans = departmentBeans;
        this.listener = listener;
        this.isSelectMe = isSelectMe;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.frag_departandgroup_depart, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        super.initData();
        initView();
        initHandle();
        presenter = new DepartmentPresenter(new DepartmentModel(), this);

        kjdb = KJDB.create(getActivity(), DbConfig.DBNAME, DbConfig.ISDEBUG, DbConfig.DBVERSION, new KJDB.DbUpdateListener() {
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                if(newVersion>oldVersion)
                {
                    Cursor cursor = db.rawQuery(
                            "SELECT name FROM sqlite_master WHERE type ='table'", null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            // 添加异常捕获.忽略删除所有表时出现的异常:
                            // table sqlite_sequence may not be dropped
                            try {
                                db.execSQL("DROP TABLE " + cursor.getString(0));
                            } catch (SQLException e) {
                                KJLoger.debug(getClass().getName() + e.getMessage());
                            }
                        }
                    }
                    if (cursor != null) {
                        cursor.close();
                        cursor = null;
                    }
                }
            }
        });
        datas = (ArrayList<GroupDataBean>) kjdb.findAllByWhere(GroupDataBean.class, "parent_department_id = 0");

        if (datas != null && datas.size() > 0) {
            refresh(datas);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
            params.put("parentDepartmentId", "0");
            presenter.getGroupDatas(params);
        }

    }

    @SuppressLint("HandlerLeak")
    void initHandle() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 10001: // 搜索有文字的的时候
                        btnSearchClear.setVisibility(View.VISIBLE);
                        break;
                    case 10002: // 搜索没文字的的时候
                        btnSearchClear.setVisibility(View.INVISIBLE);
                        break;
                    case 10003:
                        if (listener != null) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("departmentBeans", departmentBeans);
                            listener.showData(bundle);
                        }
                        break;
                }
            }
        };
    }

    private void initView() {
        deptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ChildDepartmentsBean childDepartmentsBean = (ChildDepartmentsBean) parent.getItemAtPosition(position);
//                datas = (ArrayList<GroupDataBean>) kjdb.findAllByWhere(GroupDataBean.class, "department_id = " + childDepartmentsBean.getDepartment_id());
//                if (datas != null && datas.size() > 0) {
//                    refresh(datas);
//                } else {
//                    Map<String, String> params = new HashMap<>();
//                    params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
//                    params.put("parentDepartmentId", childDepartmentsBean.getDepartment_id() + "");
//                    presenter.getGroupDatas(params);
//                }

                Bundle bundle = new Bundle();
                Intent intent = new Intent(getActivity(), Act_DepartAndGroup_Depart.class);
                bundle.putString("departmentId", childDepartmentsBean.getDepartment_id() + "");
                bundle.putSerializable("departmentBeans", ((Act_DepartAndGroup) getActivity()).departmentBeans);
                bundle.putInt("isSelectMe", isSelectMe);
                intent.putExtras(bundle);
                getActivity().startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            List depart = new ArrayList<>();
            depart.addAll(((Act_DepartAndGroup) getActivity()).departmentBeans);
            departmentBeans.clear();
            departmentBeans.addAll(depart);
            adapter_dept.notifyDataSetChanged();
        }
    }

    @Override
    @OnClick({R.id.btnSearchClear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSearchClear:
                etSearch2.setText("");
                break;
        }
    }

    @Override
    public void showGroupDatas(BaseEntity<GroupDataBean> groupBean) {
        if ("200".equals(groupBean.getStatus())) {
            datas = groupBean.getDatas();
            refresh(groupBean.getDatas());
            kjdb.save(groupBean.getDatas());
        } else {
            ViewInject.toast("获取数据失败");
        }
    }

    private void refresh(List<GroupDataBean> datas) {
        if (datas.size() > 0) {
//            List<ChildDepartmentsBean> listPerson = JSON.parseArray(datas.get(0).getChildDepartments(), ChildDepartmentsBean.class);
//            List<UsersBean> usersBeen = JSON.parseArray(datas.get(0).getUsers(), UsersBean.class);

            List<GroupDataBean> listPerson = datas.get(0).getChildDepartments();
            List<UsersBean> usersBeen = datas.get(0).getUsers();

            adapter_dept = new DepartAndGroup_Depart_Adapter(deptList, listPerson, R.layout.item_department, departmentBeans, handler, isSelectMe);
            deptList.setAdapter(adapter_dept);

            peoples.clear();
            for (int i = 0; i < usersBeen.size(); i++) {
                People people = new People();
                if (usersBeen.get(i).getAccount_id() != null) {
                    //TODO 需要使用account_id
                    people.setUserId(usersBeen.get(i).getAccount_id());
                } else {
                    people.setUserId(usersBeen.get(i).getUser_id());
                }
                people.setUserName(usersBeen.get(i).getUser_name());
                people.setJobNum(usersBeen.get(i).getJobNum());
                people.setPinyin(usersBeen.get(i).getPinyin());
                peoples.add(people);
            }
            addMemberAdapter = new AddMemberAdapter(getActivity(), peoples, usersBeans_origin, handler, 0, peopleList, true);
            peopleList.setAdapter(addMemberAdapter);
            emptyLayout.dismiss();
        }
    }

}
